package com.bankcomm.iccard;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.nfc.NfcAdapter;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bankcomm.R;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.BaseViewCopy;
import com.bankcomm.ui.specialwidget.DigitPasswordKeyPad;
import com.rytong.tools.crypto.AESCipher;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;
import com.zc.card.AudioCardManager;
import com.zc.card.NFCCardManager;

public class BaseActivity extends BaseViewCopy {
	BroadcastReceiver audioDeviceReceiver;
	protected LinearLayout CardListItem;
	private LinearLayout logListLayout;
	String iccard_balance_query_body = "ewp_tran_action=" + Utils.escapeURIComponent("iccard_balance_query") + "&account=";
	Dialog dlg;
	public Object manager;

	private NfcAdapter nfcAdapter;
	private PendingIntent pendingIntent;
	public static Parcelable parcelNfc = null;

	public static String[][] TECHLISTS;
	public static IntentFilter[] FILTERS;
	boolean connectNFCDevice = false;
	protected AudioCardManager cardManager;
	public boolean isAudioAdapterConnect = false;

	public HashMap<String, String> mapSubMoney = new HashMap<String, String>();
	public HashMap<String, String> mapSubList = new HashMap<String, String>();
	public Dialog mDialog;
	private String[] cardInfoArray;

	private static int CLOSE_DIALOG_TAG = 1001;
	private static int SHOW_DIALOG_TAG = 1002;
	private static int TOAST_ERROR_INFO = 1003;
	private static int SHOW_NOTIFICATIONS = 1004;
	private static int RESET_STREAM_VOLUME = 1005;

	String strInfo = "er";
	private byte[] passwordKey_;
	String moneyTmp = "";
	double moneyCardBalance = 0;
	private int currentVolumeNum;
	private AudioManager am;
	public DigitPasswordKeyPad dpk;
	private int currentNotiVolumeNum;
	private int currentRingVolumeNum;
	private NotificationManager notificationManager;
	private Notification notifcation;
	private PendingIntent contentIntent;
	private PhoneStateReceiver phoneStateReceiver;
	protected static long lastClickTime;

	static {
		try {
			TECHLISTS = new String[][] { { IsoDep.class.getName() }, { NfcV.class.getName() }, { NfcF.class.getName() }, };

			FILTERS = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") };
		} catch (Exception e) {

		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		createHandlerForAudioCard();
		registerAudioReceiver();
		registerPhoneStateReceiver();
		// parcelNfc = BaseView.mid_.parcelNfc;
		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
		pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		createProgressDialog();
		onNewIntent(getIntent());
	}
    /**
     * 创建加载弹出框
     * 
     * **/
	private void createProgressDialog() {
		mDialog=LPMid.getInstance().creatDialog(mDialog,getString(R.string.onMapLoading),this);
		mDialog.setCanceledOnTouchOutside(false);
	}

	@Override
	protected void onNewIntent(Intent intent) {

		parcelNfc = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

		if (null != parcelNfc) {
			connectNFCDevice = true;
			new Thread(new Runnable() {

				@Override
				public void run() {
					handlerChooseActivity(BaseActivity.this);
				}
			}).start();

		} else {
			connectNFCDevice = false;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (nfcAdapter != null) {
			nfcAdapter.disableForegroundDispatch(this);
		}
	}

	@Override
	public void onResume() {
		super.onResume();

		if (nfcAdapter != null) {
			nfcAdapter.enableForegroundDispatch(this, pendingIntent, FILTERS, TECHLISTS);
		}
	}
    /**
     * 注册监听耳机的广播接收器
     * 
     * **/
	public void registerAudioReceiver() {
		if (null == audioDeviceReceiver) {
			audioDeviceReceiver = new HeadsetPlugReceiver();
		}
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_HEADSET_PLUG);
		registerReceiver(audioDeviceReceiver, filter);
	}
	  /**
     * 注册监听来电状态的广播接收器
     * 
     * **/
	public void registerPhoneStateReceiver() {
		if (null == phoneStateReceiver) {
			phoneStateReceiver = new PhoneStateReceiver();
		}
		IntentFilter filter = new IntentFilter();
		filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
		registerReceiver(phoneStateReceiver, filter);
	}

	/**
	 * 创建handler处理监听音频卡
	 **/
	public void createHandlerForAudioCard() {
		EventHandler uhandler = new EventHandler();
		uhandler.eventHandler = new Handler() {
			public void handleMessage(Message msg) {
                //处理打开音频口交互管理器
				if (null != msg && msg.what == 1000) {
					setVolumeMax();
					setNotificationsAndRingVolumeMin();
					openDeviceAndGetCardInfo(BaseActivity.this);
				}
				//关闭加载框
				if (null != msg && msg.what == CLOSE_DIALOG_TAG) {
					if (mDialog.isShowing())
						mDialog.dismiss();
				}
				//显示加载框
				if (null != msg && msg.what == SHOW_DIALOG_TAG) {
					mDialog.show();
				}
				//模仿toast出现异常时提示
				if (null != msg && msg.what == TOAST_ERROR_INFO) {
					String errorInfo = (String) msg.obj;
					LPToastUtil.getInstance().getToast(errorInfo,
							BaseActivity.this);

				}
				//显示出notification
				if (null != msg && msg.what == SHOW_NOTIFICATIONS) {
					showNotification(getString(R.string.tel_notice), getString(R.string.app_name), getString(R.string.tel_notice),
							R.string.app_name, R.drawable.icon);
				}
				//重新恢复声音大小
				if (null != msg && msg.what == RESET_STREAM_VOLUME) {
					reSetStreamVolume();
				}
			}
		};
	}

	/**
	 * 打开音频设备进行操作
	 **/
	public void openDeviceAndGetCardInfo(final Activity context) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				cardManager = new AudioCardManager();
				manager = cardManager;
				// RIGHT
				handlerChooseActivity(context);

			}
		}).start();
	}

	// 将多媒体声音设置到最大
	protected void setVolumeMax() {
		am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		currentVolumeNum = am.getStreamVolume(AudioManager.STREAM_MUSIC);
		am.setStreamVolume(AudioManager.STREAM_MUSIC, max, 0);

	}
	 /**
     * 设置短信声和铃声为静音
     * **/
	protected void setNotificationsAndRingVolumeMin() {
		am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		currentNotiVolumeNum = am.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
		currentRingVolumeNum = am.getStreamVolume(AudioManager.STREAM_RING);
		am.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0);
		am.setStreamVolume(AudioManager.STREAM_RING, 0, 0);

	}

	public void closeDialog() {
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Message m = new Message();
					m.what = CLOSE_DIALOG_TAG;
					Handler handler = EventHandler.ut.eventHandler;
					Thread.sleep(500);
					handler.sendMessage(m);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		t.start();
	}

	public void showDialog() {
		Message m = new Message();
		m.what = SHOW_DIALOG_TAG;
		Handler handler = EventHandler.ut.eventHandler;
		handler.sendMessage(m);
	}

	public void sendError(String error) {
		Message m = new Message();
		m.what = TOAST_ERROR_INFO;
		m.obj = error;
		Handler handler = EventHandler.ut.eventHandler;
		handler.sendMessage(m);
	}
	  /**
     * 处理三个activity交易的入口
     * 
     * **/
	protected void handlerChooseActivity(Activity context) {

		if (context instanceof ICCard_Balance_Query_Activity) {
			showDialog();
			// 余额查询
			handlerIccardBalance(context);
		}
		if (context instanceof ICCard_Deal_Logquery_Activity) {
			showDialog();
			// 查询所有记录
			handlerIccardDealLog(context);
		}
		if (context instanceof ICCard_Cash_Load_Activity) {
			// 圈存
			if (((ICCard_Cash_Load_Activity) context).layout_Input_Money.isShown()) {
				showDialog();
				handlerIccard_cash_load_Query(context);
			}
		}
	}

	/**
	 * 处理圈存交易
	 **/
	protected void handlerIccard_cash_load_Query(final Activity act) {
		// 音频卡优先
		if (isAudioAdapterConnect) {
			strInfo = cardManager.GetCardInfo();
		} else if (connectNFCDevice) {
			strInfo = NFCCardManager.GetCardInfo(parcelNfc);
		}
		// final String s =
		// "6222620110003251817|000000010000|ER TONG KA YI|00|310100199012161688";
		final ICCard_Cash_Load_Activity iclActivity = (ICCard_Cash_Load_Activity) act;
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				iclActivity.cleanView();
			}
		});

		final LinearLayout layoutIm = iclActivity.layout_Input_Money;
		iclActivity.notAllowSub = true;
		if (strInfo.length() == 2) {
			sendError(getString(R.string.errorAudioInfo));
			closeDialog();
		} else {

			boolean stopSub = false;
			try {
				Utils.printOutToConsole("cardInfoArray  -------  >>>" + cardInfoArray);
				cardInfoArray = strInfo.split("\\|");
				String url = ConfigManager.ICCARD_URL_S;
				String body = iccard_balance_query_body + Utils.escapeURIComponent(cardInfoArray[0]);
//				body = DESCipher.doEncrypt(body, AESCipher.serverKey_);
				body = AESCipher.encrypt(body, AESCipher.clientKey_, AESCipher.clientIv_);

				moneyTmp = (String) LPMid.getInstance().hm_.sendPostRequest(url, body, null, null, null);
				moneyTmp = AESCipher.decrypt(moneyTmp, AESCipher.serverKey_, AESCipher.serverIv_);
				mapSubMoney.put("accountbalence", moneyTmp);
				iclActivity.notAllowSub=true;
			} catch (Exception e) {
				stopSub = true;
				moneyTmp = "";
//				LPMid.getInstance().alert(BaseActivity.this, e.getMessage(), false);
				handleException(e.getMessage());
				mapSubMoney.clear();
				iclActivity.notAllowSub=false;
			} finally {
				if (stopSub) {
					mapSubMoney.clear();
				}
			}

			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (layoutIm.isShown()) {
						iclActivity.readInfoPan = cardInfoArray[0];
						iclActivity.tvm_ICCard.setText(getString(R.string.iccardNum).concat(cardInfoArray[0]));
						iclActivity.tvm_AccountBalance.setText(getString(R.string.accountbalance).concat(moneyTmp));

						try {
							String str = CardHandlerUtils.handler12toDecimal(cardInfoArray[1]);
							moneyCardBalance = Double.parseDouble(str);
							iclActivity.tvm_CardBalance.setText(getString(R.string.cardbalance).concat(str));
							Double num = 1000.00 - Double.parseDouble(str);
							BigDecimal d=new BigDecimal(num);
							d=d.setScale(2,BigDecimal.ROUND_HALF_UP);
							double b=d.doubleValue();
							iclActivity.etm_StoreMoney.setHint("最多" + b + "元");
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						mapSubMoney.put("iccardid", cardInfoArray[0]);
						mapSubMoney.put("cardbalance", cardInfoArray[1]);
					}
				}
			});
		}
		closeDialog();
	}

	/**
	 * 处理余额显示
	 **/

	public void handlerIccardBalance(final Activity act) {
		if (isAudioAdapterConnect) {
			strInfo = cardManager.GetCardInfo();
		} else if (connectNFCDevice) {
			strInfo = NFCCardManager.GetCardInfo(parcelNfc);
		}
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				((ICCard_Balance_Query_Activity) act).cleanView();
			}
		});

		if (strInfo.length() == 2) {
			sendError(getString(R.string.errorAudioInfo));
			closeDialog();
		} else {

			// TODO Auto-generated method stub
			final String[] cardInfoArray = strInfo.split("\\|");
			String url = ConfigManager.ICCARD_URL_S;
			String body = iccard_balance_query_body + Utils.escapeURIComponent(cardInfoArray[0]);
			try {
//				body = DESCipher.doEncrypt(body, AESCipher.serverKey_);
				body = AESCipher.encrypt(body, AESCipher.clientKey_, AESCipher.clientIv_);
				moneyTmp = (String)LPMid.getInstance().hm_.sendPostRequest(url, body, null, null, null);
				moneyTmp = AESCipher.decrypt(moneyTmp, AESCipher.serverKey_, AESCipher.serverIv_);
			} catch (Exception e) {
				moneyTmp = "";
//				LPMid.getInstance().alert(BaseActivity.this, e.getMessage(), false);
			
				handleException(e.getMessage());
			}
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					((ICCard_Balance_Query_Activity) act).tvICCard_ID.setText(getString(R.string.iccardNum).concat(cardInfoArray[0]));
					((ICCard_Balance_Query_Activity) act).tvAccountBalance.setText(getString(R.string.accountbalance).concat(moneyTmp));
					((ICCard_Balance_Query_Activity) act).ic_balance_query_prompt.setVisibility(View.GONE);
					((ICCard_Balance_Query_Activity) act).ic_balancequery_prompt_pic.setVisibility(View.GONE);
					try {
						((ICCard_Balance_Query_Activity) act).tvCard_Balance.setText(getString(R.string.cardbalance).concat(
								CardHandlerUtils.handler12toDecimal(cardInfoArray[1])));
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		}
		closeDialog();
	}

	/**
	 * 处理交易日志
	 **/
	public void handlerIccardDealLog(final Activity act) {
		// String s = cardManager.QueryLog();
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				logListLayout = (LinearLayout) ((ICCard_Deal_Logquery_Activity) act).findViewById(R.id.contentloglist);
				logListLayout.removeAllViews();
			}
		});

		if (isAudioAdapterConnect) {
			strInfo = cardManager.QueryLog();
		} else if (connectNFCDevice) {
			strInfo = NFCCardManager.QueryLog(parcelNfc);
		}
		if (strInfo.length() == 2) {
			sendError(getString(R.string.errorAudioInfo));
			closeDialog();
		} else {

			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					((ICCard_Deal_Logquery_Activity)act).ic_deal_log_prompt.setVisibility(View.GONE);
					if (strInfo.contains("|")) {
						String cardId = strInfo.substring(0, 19);
						String logStr = strInfo.substring(20, strInfo.length());

						final String[] logArray = logStr.split("\\|");

						TextView tvicid = (TextView) ((ICCard_Deal_Logquery_Activity) act).findViewById(R.id.iccardid);
						tvicid.setText(getString(R.string.iccardNum) + cardId);
						for (String string : logArray) {
							addLogListView(string, logListLayout);
						}
					} else {
						TextView tvicid = (TextView) ((ICCard_Deal_Logquery_Activity) act).findViewById(R.id.iccardid);
						tvicid.setText(getString(R.string.iccardNum) + strInfo);
					}
				}
			});
		}
		closeDialog();
	}

	  /**
     * 交易日志具体item
     * @param str 单个数据
     * @param logList 交易单个日志父容器
     * **/
	void addLogListView(final String str, LinearLayout logList) {

		CardListItem = (LinearLayout) LayoutInflater.from(BaseActivity.this).inflate(R.layout.iccard_list_item, null);
		TextView tvDealDate = (TextView) CardListItem.findViewById(R.id.dealdate);
		TextView tvDealType = (TextView) CardListItem.findViewById(R.id.dealtype);
		TextView tvCompanies = (TextView) CardListItem.findViewById(R.id.companies);
		TextView tvDealMoney = (TextView) CardListItem.findViewById(R.id.dealmoney);

		try {
			tvDealDate.setText(getString(R.string.dealdate).concat(CardHandlerUtils.handlerDateFormat(str.substring(0, 6))));
		} catch (ParseException e1) {

		}
		tvDealType.setText(getString(R.string.dealtype).concat(CardHandlerUtils.handlerDealType(BaseActivity.this, str.substring(84, 86))));

		try {
			String Companies = CardHandlerUtils.hexStr2Str(str.substring(44, 84));
			if (Companies.equals("")) {
				Companies = getString(R.string.unknownstr);
			}
			tvCompanies.setText(getString(R.string.companies).concat(Companies));
		} catch (UnsupportedEncodingException e) {

		}
		try {
			tvDealMoney.setText(getString(R.string.dealmoney).concat(CardHandlerUtils.handler12toDecimal(str.substring(12, 24))));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logList.addView(CardListItem);
		((LinearLayout.LayoutParams) CardListItem.getLayoutParams()).bottomMargin = 10;

	}


	public void startActivity(Activity activity, String action, Bundle bundle, boolean finishCurr) {
		Intent intent = new Intent();
		intent.setAction(action);
		intent.putExtras(bundle);
		activity.startActivity(intent);
		if (finishCurr) {
			activity.finish();
		}
	}

	// System.out.println(str.substring(0, 6));
	// System.out.println(str.substring(6, 12));
	// System.out.println(str.substring(12, 24));
	// System.out.println(str.substring(24, 36));
	// System.out.println(str.substring(36, 40));
	// System.out.println(str.substring(40, 44));
	// System.out.println(str.substring(44, 84));
	// System.out.println(str.substring(84, 86));
	// System.out.println(str.substring(86, 90));
	  /**
     * 在activity結束时注销监听
     * **/
	@Override
	public void finish() {
		super.finish();
		if(audioDeviceReceiver!=null){
		unregisterReceiver(audioDeviceReceiver);
		unregisterReceiver(phoneStateReceiver);
		audioDeviceReceiver=null;
		phoneStateReceiver=null;
		}
	}
	  /**
     * 重置声音
     * **/
	void reSetStreamVolume() {
		if (am != null) {
			am.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolumeNum, 0);
			am.setStreamVolume(AudioManager.STREAM_NOTIFICATION, currentNotiVolumeNum, 0);
			am.setStreamVolume(AudioManager.STREAM_RING, currentRingVolumeNum, 0);
		}
	}

	/** 防止在短时间重复点击 **/
	public static boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 800) {
			return true;
		}
		lastClickTime = time;
		return false;
	}
	  /**
     * 在状态栏显示notification
     * @param tickerText notification显示时的文字
     * @param  contentTitle 拉下状态栏显示的title
     * @param contentText 拉下状态栏显示的文字内容
     * **/
	private void showNotification(String tickerText, String contentTitle, String contentText, int id, int resId) {
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notifcation = new Notification(resId, tickerText, System.currentTimeMillis());

		// contentIntent = PendingIntent.getActivity(this, 0, getIntent(), 0);
		notifcation.flags = Notification.FLAG_AUTO_CANCEL;
		notifcation.setLatestEventInfo(this, contentTitle, contentText, null);
		notificationManager.notify(id, notifcation);

	}
	
}
